import React, { useCallback, useMemo } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import {
  MoreVertical,
  Settings,
  X,
  TrendingUp,
  TrendingDown,
  Users,
  MessageSquare,
  Rocket,
  Activity,
  Cpu,
  HardDrive,
  Wifi,
  Clock,
  AlertTriangle,
  CheckCircle,
  BarChart3,
  PieChart,
  LineChart,
  Monitor,
  Database,
  Network,
  Server,
  Zap,
  Calendar,
  FileText,
  Settings as SettingsIcon,
  Eye,
  Shield
} from 'lucide-react';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { CSS } from '@dnd-kit/utilities';
import { useSortable } from '@dnd-kit/sortable';
import { SystemMonitor } from '@/components/SystemMonitor';

/**
 * 小部件类型定义
 */
export type WidgetType = 
  | 'stats' 
  | 'chart' 
  | 'progress' 
  | 'activity' 
  | 'system' 
  | 'quick-actions';

/**
 * 小部件数据接口
 */
export interface WidgetData {
  id: string;
  type: WidgetType;
  title: string;
  size: 'small' | 'medium' | 'large';
  data?: any;
  position: { x: number; y: number };
  isVisible: boolean;
  config?: {
    showIcon?: boolean;
    showTrend?: boolean;
    refreshInterval?: number;
    chartType?: 'line' | 'bar' | 'pie';
  };
}

/**
 * 小部件组件属性
 */
interface DashboardWidgetProps {
  widget: WidgetData;
  isLayoutMode?: boolean;
  onEdit?: (widget: WidgetData) => void;
  onRemove?: (widgetId: string) => void;
  onToggle?: (widgetId: string, enabled: boolean) => void;
  onNavigate?: (path: string) => void;
  isDragging?: boolean;
}

/**
 * 获取小部件图标
 */
const getWidgetIcon = (type: WidgetType | 'system-monitor') => {
  const iconMap = {
    stats: BarChart3,
    chart: LineChart,
    progress: PieChart,
    activity: Clock,
    system: Cpu,
    'quick-actions': Rocket,
    'system-monitor': Monitor
  };
  const Icon = iconMap[type as keyof typeof iconMap];
  return <Icon className="w-5 h-5" />;
};

/**
 * 渲染统计小部件内容
 */
const renderStatsWidget = (data: any, config: any) => {
  const { value, label, change, changeType, icon } = data;
  
  return (
    <div className="space-y-2">
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-2">
          {config?.showIcon && icon && (
            <div className="p-2 bg-primary/10 rounded-lg">
              {icon}
            </div>
          )}
          <div>
            <p className="text-2xl font-bold">{value}</p>
            <p className="text-sm text-muted-foreground">{label}</p>
          </div>
        </div>
        {config?.showTrend && change !== undefined && (
          <div className="flex items-center space-x-1">
            {changeType === 'increase' ? (
              <TrendingUp className="w-4 h-4 text-green-500" />
            ) : (
              <TrendingDown className="w-4 h-4 text-red-500" />
            )}
            <span className={`text-sm ${
              changeType === 'increase' ? 'text-green-500' : 'text-red-500'
            }`}>
              {Math.abs(change)}%
            </span>
          </div>
        )}
      </div>
    </div>
  );
};

/**
 * 渲染进度小部件内容
 */
const renderProgressWidget = (data: any) => {
  const { items } = data;
  
  return (
    <div className="space-y-3">
      {items?.map((item: any, index: number) => (
        <div key={index} className="space-y-1">
          <div className="flex justify-between text-sm">
            <span>{item.label}</span>
            <span>{item.value}%</span>
          </div>
          <Progress value={item.value} className="h-2" />
        </div>
      ))}
    </div>
  );
};

/**
 * 渲染活动小部件内容
 */
const renderActivityWidget = (data: any) => {
  const { activities } = data;
  
  return (
    <div className="space-y-3">
      {activities?.slice(0, 3).map((activity: any, index: number) => (
        <div key={index} className="flex items-start space-x-3">
          <div className="flex-shrink-0">
            <div className={`w-2 h-2 rounded-full ${
              activity.type === 'success' ? 'bg-green-500' :
              activity.type === 'warning' ? 'bg-yellow-500' :
              activity.type === 'error' ? 'bg-red-500' : 'bg-blue-500'
            }`} />
          </div>
          <div className="flex-1 min-w-0">
            <p className="text-sm font-medium truncate">{activity.title}</p>
            <p className="text-xs text-muted-foreground">{activity.time}</p>
          </div>
        </div>
      ))}
    </div>
  );
};

/**
 * 渲染系统小部件内容
 */
const renderSystemWidget = (data: any) => {
  const { metrics } = data;
  
  return (
    <div className="space-y-3">
      {metrics?.map((metric: any, index: number) => (
        <div key={index} className="flex items-center justify-between">
          <div className="flex items-center space-x-2">
            {metric.icon}
            <span className="text-sm">{metric.name}</span>
          </div>
          <div className="flex items-center space-x-2">
            <span className="text-sm font-medium">{metric.value}%</span>
            <div className={`w-2 h-2 rounded-full ${
              metric.status === 'normal' ? 'bg-green-500' :
              metric.status === 'warning' ? 'bg-yellow-500' : 'bg-red-500'
            }`} />
          </div>
        </div>
      ))}
    </div>
  );
};

/**
 * 渲染快速操作小部件内容
 */
const renderQuickActionsWidget = (data: any, onAction?: (action: string) => void) => {
  const { actions } = data;
  
  return (
    <div className="grid grid-cols-2 gap-2">
      {actions?.map((action: any, index: number) => (
        <Button
          key={index}
          variant="outline"
          size="sm"
          className="h-auto p-3 flex flex-col items-center space-y-1"
          onClick={() => onAction?.(action.id)}
          disabled={!action.enabled}
        >
          {action.icon}
          <span className="text-xs">{action.label}</span>
        </Button>
      ))}
    </div>
  );
};

/**
 * 生成小部件数据的函数
 */
const generateWidgetData = (type: WidgetType) => {
  switch (type) {
    case 'stats':
      return {
        value: '1,234',
        label: '总用户数',
        change: 12,
        changeType: 'increase',
        icon: <Users className="w-4 h-4" />
      };
    case 'chart':
      return {
        labels: ['1月', '2月', '3月', '4月', '5月', '6月'],
        datasets: [{
          label: '用户增长',
          data: [65, 59, 80, 81, 56, 55],
          borderColor: 'rgb(75, 192, 192)',
          backgroundColor: 'rgba(75, 192, 192, 0.2)',
        }]
      };
    case 'progress':
      return {
        items: [
          { label: 'CPU 使用率', value: 65 },
          { label: '内存使用率', value: 78 },
          { label: '磁盘使用率', value: 45 }
        ]
      };
    case 'activity':
      return {
        activities: [
          { title: '用户登录', time: '2分钟前', type: 'success' },
          { title: '系统更新', time: '5分钟前', type: 'info' },
          { title: '错误报告', time: '10分钟前', type: 'error' }
        ]
      };
    case 'system':
      return {
        metrics: [
          { label: 'CPU', value: 65, status: 'normal' },
          { label: '内存', value: 78, status: 'warning' },
          { label: '磁盘', value: 45, status: 'normal' }
        ]
      };
    case 'quick-actions':
      return {
        actions: [
          { id: 'add-user', label: '添加用户', icon: <Users className="w-4 h-4" />, enabled: true },
          { id: 'create-report', label: '生成报告', icon: <FileText className="w-4 h-4" />, enabled: true },
          { id: 'system-settings', label: '系统设置', icon: <SettingsIcon className="w-4 h-4" />, enabled: true },
          { id: 'view-logs', label: '查看日志', icon: <Activity className="w-4 h-4" />, enabled: true }
        ]
      };
    default:
      return null;
  }
};

/**
 * 可拖拽的仪表盘小部件组件
 */
export const DashboardWidget: React.FC<DashboardWidgetProps> = React.memo(({
  widget,
  isLayoutMode = false,
  onEdit,
  onRemove,
  onToggle,
  onNavigate,
  isDragging = false
}) => {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
  } = useSortable({ id: widget.id });

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.5 : 1,
  };

  // 使用 useMemo 缓存生成的数据，避免无限重新渲染
  const widgetData = useMemo(() => {
    return widget.data || generateWidgetData(widget.type);
  }, [widget.data, widget.type]);

  // 使用useCallback优化回调函数，防止无限重新渲染
  const handleEdit = useCallback(() => {
    onEdit?.(widget);
  }, [onEdit, widget]);

  const handleToggle = useCallback(() => {
    onToggle?.(widget.id, !widget.isVisible);
  }, [onToggle, widget.id, widget.isVisible]);

  const handleRemove = useCallback(() => {
    onRemove?.(widget.id);
  }, [onRemove, widget.id]);

  const handleQuickAction = useCallback((actionId: string) => {
    const actionRoutes: Record<string, string> = {
      'add-user': '/users',
      'create-report': '/analytics',
      'system-settings': '/settings',
      'view-logs': '/logs'
    };
    const route = actionRoutes[actionId];
    if (route && onNavigate) {
      onNavigate(route);
    }
  }, [onNavigate]);

  /**
   * 渲染小部件内容
   */
  const renderWidgetContent = () => {
    if (!widget.isVisible) {
      return (
        <div className="flex items-center justify-center h-32 text-muted-foreground">
          <div className="text-center">
            <div className="w-8 h-8 mx-auto mb-2 opacity-50">
              {getWidgetIcon(widget.type)}
            </div>
            <p className="text-sm">小部件已隐藏</p>
          </div>
        </div>
      );
    }

    switch (widget.type) {
      case 'stats':
        return renderStatsWidget(widgetData, widget.config);
      case 'progress':
        return renderProgressWidget(widgetData);
      case 'activity':
        return renderActivityWidget(widgetData);
      case 'system':
        return renderSystemWidget(widgetData);
      case 'quick-actions':
        return renderQuickActionsWidget(widgetData, handleQuickAction);
      case 'system-monitor':
        return <SystemMonitor />;
      case 'chart':
        return (
          <div className="flex items-center justify-center h-32 text-muted-foreground">
            <div className="text-center">
              <BarChart3 className="w-8 h-8 mx-auto mb-2" />
              <p className="text-sm">图表功能开发中</p>
            </div>
          </div>
        );
      default:
        return (
          <div className="flex items-center justify-center h-32 text-muted-foreground">
            <p className="text-sm">未知小部件类型</p>
          </div>
        );
    }
  };

  return (
    <div
      ref={setNodeRef}
      style={style}
      className={`${widget.size === 'large' ? 'col-span-2' : ''} ${!widget.isVisible ? 'opacity-60' : ''} ${isLayoutMode ? 'ring-2 ring-primary/20' : ''}`}
    >
      <Card className={`h-full ${isDragging ? 'shadow-lg' : ''}`}>
        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
          <CardTitle className="text-sm font-medium flex items-center space-x-2">
            <div 
              {...attributes} 
              {...listeners}
              className="cursor-grab active:cursor-grabbing p-1 hover:bg-muted rounded"
            >
              {getWidgetIcon(widget.type)}
            </div>
            <span>{widget.title}</span>
            {!widget.isVisible && (
              <Badge variant="secondary" className="text-xs">
                已隐藏
              </Badge>
            )}
            {isLayoutMode && (
              <Badge variant="outline" className="text-xs">
                可拖拽
              </Badge>
            )}
          </CardTitle>
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="ghost" size="sm" className="h-8 w-8 p-0">
                <MoreVertical className="h-4 w-4" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuItem onClick={handleEdit}>
                <Settings className="mr-2 h-4 w-4" />
                配置
              </DropdownMenuItem>
              <DropdownMenuItem onClick={handleToggle}>
                {widget.isVisible ? (
                  <>
                    <X className="mr-2 h-4 w-4" />
                    隐藏
                  </>
                ) : (
                  <>
                    <CheckCircle className="mr-2 h-4 w-4" />
                    显示
                  </>
                )}
              </DropdownMenuItem>
              <DropdownMenuItem 
                onClick={handleRemove}
                className="text-red-600"
              >
                <X className="mr-2 h-4 w-4" />
                移除
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </CardHeader>
        <CardContent>
          {renderWidgetContent()}
        </CardContent>
      </Card>
    </div>
  );
});

export default DashboardWidget;